package com.jzo2o.market.handler;

import com.jzo2o.api.customer.CommonUserApi;
import com.jzo2o.api.customer.dto.response.CommonUserResDTO;
import com.jzo2o.common.utils.DateUtils;
import com.jzo2o.common.utils.IdUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.domain.CouponUser;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponUserService;
import com.jzo2o.redis.handler.SyncProcessHandler;
import com.jzo2o.redis.model.SyncMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.jzo2o.market.constants.RedisConstants.RedisKey.COUPON_SEIZE_SYNC_QUEUE_NAME;

/**
 * 抢单成功同步任务
 */
@Component(COUPON_SEIZE_SYNC_QUEUE_NAME)
@Slf4j
public class SeizeCouponSyncProcessHandler implements SyncProcessHandler<Object> {

    @Resource
    private ICouponService couponService;

    @Resource
    private ICouponUserService couponUserService;

    @Resource
    private CommonUserApi commonUserApi;


    @Override
    public void batchProcess(List<SyncMessage<Object>> multiData) {
        throw new RuntimeException("不支持批量处理");
    }

    /**
     * signleData key activityId, value 抢单用户id
     *
     * @param singleData
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void singleProcess(SyncMessage<Object> singleData) {
        log.info("抢单结果同步开始 id ： {}", singleData.getKey());
        long couponId = NumberUtils.parseLong(singleData.getValue().toString());
        long userId = NumberUtils.parseLong(singleData.getKey());
        // 1.获取活动
        Coupon coupon = couponService.getById(couponId);
        if (coupon == null) {
            return;
        }
        CommonUserResDTO commonUserResDTO = commonUserApi.findById(userId);
        if (commonUserResDTO == null) {
            return;
        }
        // 2.新增优惠券
        CouponUser couponUser = new CouponUser();
        couponUser.setId(IdUtils.getSnowflakeNextId());
        couponUser.setCouponId(couponId);
        couponUser.setUserId(userId);
        couponUser.setUserName(commonUserResDTO.getNickname());
        couponUser.setUserPhone(commonUserResDTO.getPhone());
        couponUser.setName(coupon.getName());
        couponUser.setType(coupon.getType());
        couponUser.setDiscountAmount(coupon.getDiscountAmount());
        couponUser.setDiscountRate(coupon.getDiscountRate());
        couponUser.setAmountCondition(coupon.getAmountCondition());
        couponUser.setValidityTime(DateUtils.now().plusDays(coupon.getValidityDays()));
        couponUser.setStatus(CouponStatusEnum.NO_USE.getStatus());

        couponUserService.save(couponUser);
    }
}
